<template>
  <div class="order-confirm-page">
    <!-- 头部导航 -->
    <div class="order-header">
      <div class="header-title">确认订单</div>
    </div>
    
    <!-- 订单内容区 - 左右分栏布局 -->
    <div class="main-content">
      <!-- 左侧内容区 -->
      <div class="left-content">
        <!-- 收货地址模块 -->
        <div class="address-section">
          <div class="section-title">确认收货地址</div>
          <div class="address-actions">
            <el-button size="small" @click="openAddAddress">使用新地址</el-button>
            <el-button size="small" @click="manageAddress">管理地址</el-button>
          </div>
          
          <!-- 地址卡片一行排三个 -->
          <div v-if="addresses.length === 0" class="no-address">
            <p>您还没有添加收货地址</p>
            <el-button type="primary" @click="openAddAddress">新增地址</el-button>
          </div>
          <div v-else class="address-cards">
            <div 
              v-for="(address) in addresses" 
              :key="address.id" 
              class="address-card" 
              :class="{ 'selected': selectedAddressId === address.id }"
              @click="selectAddress(address.id)"
            >
              <div class="address-header">
                <span class="address-name">{{ address.name }}</span>
                <span class="address-phone">{{ maskPhone(address.phone) }}</span>
                <span v-if="address.isDefault === '1'" class="default-tag">默认</span>
              </div>
              <div class="address-detail">
                <span>{{ address.province || '' }}{{ address.city || '' }}{{ address.district || '' }}{{ address.detail || '' }}</span>
              </div>
              <div class="address-selected-marker" v-if="selectedAddressId === address.id">
                <div class="check-icon"></div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 订单商品信息 -->
        <div class="order-items-section">
          <div class="section-title">确认订单信息</div>
          <div class="order-items">
            <div v-if="selectedItems.length === 0" class="no-items">
              <p>没有选中的商品</p>
            </div>
            <div v-else>
              <!-- 按店铺分组显示商品 -->
              <div v-for="store in groupedItems" :key="store.id" class="store-group">
                <div class="store-name">{{ store.name }}</div>
                <div class="items">
                  <div v-for="item in store.items" :key="item.id" class="item">
                    <div class="item-info">
                      <div class="item-image">
                        <img :src="item.image" alt="{{ item.title }}" />
                      </div>
                      <div class="item-details">
                        <div class="item-title">{{ item.title }}</div>
                        <div class="item-spec">{{ formatSpec(item.spec) }}</div>
                        <div class="item-price-count">
                          <span class="item-price">￥{{ item.price.toFixed(2) }}</span>
                          <span class="item-count">x{{ item.num }}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            
            <!-- 商品数量汇总 -->
            <div class="items-summary">
              <div class="summary-row">
                <span class="summary-label">商品件数：</span>
                <span class="summary-value">{{ totalCount }}件</span>
              </div>
              <div class="summary-row">
                <span class="summary-label">商品总价：</span>
                <span class="summary-value price">￥{{ totalPrice.toFixed(2) }}</span>
              </div>
            </div>
            </div>
          </div>
        </div>
        
        <!-- 订单备注 -->
        <div class="order-remark-section">
          <div class="section-title">订单备注</div>
          <div class="remark-input">
            <textarea v-model="orderRemark" placeholder="选填，可填写备注信息" maxlength="200"></textarea>
            <span class="remark-count">{{ orderRemark.length }}/200</span>
          </div>
        </div>
        
        <!-- 配送服务 -->
        <!-- <div class="delivery-section">
          <div class="section-title">配送服务</div>
          <div class="delivery-options">
            <div class="delivery-option">
              <div class="option-name">
                <input type="checkbox" checked disabled />
                <span>快递</span>
              </div>
              <div class="option-desc">预计20小时内发货(详情页3天内发货)</div>
              <div class="option-price">￥0.00</div>
            </div>
            
            <div class="delivery-option">
              <div class="option-name">
                <input type="checkbox" v-model="enableInsurance" />
                <span>运费险</span>
              </div>
              <div class="option-desc">退货可赔付5元</div>
              <div class="option-price">￥4.53</div>
            </div>
          </div>
        </div> -->
      </div>
      <!-- 右侧内容区 -->
      <div class="right-content">
        <!-- 付款详情 -->
        <div class="payment-details">
          <div class="section-title">付款详情 共{{ totalCount }}件商品</div>
          <div class="price-items">
            <div class="price-item">
              <span class="price-label">商品总价</span>
              <span class="price-value">￥{{ totalPrice.toFixed(2) }}</span>
            </div>
            <div class="price-item">
              <span class="price-label">运费</span>
              <span class="price-value">￥0.00</span>
            </div>
          </div>
          
          <!-- 支付方式 -->
          <div class="payment-methods">
            <!-- <div class="section-title">支付方式</div> -->
            <!-- <div class="payment-options">
              <div class="payment-option" :class="{ 'selected': selectedPayment === 'alipay' }" @click="selectPayment('alipay')">
                <input type="radio" name="payment" :checked="selectedPayment === 'alipay'" />
                <span class="payment-name">支付宝</span>
              </div>
              <div class="payment-option" :class="{ 'selected': selectedPayment === 'installment' }" @click="selectPayment('installment')">
                <input type="radio" name="payment" :checked="selectedPayment === 'installment'" />
                <span class="payment-name">分期付款</span>
                <span class="installment-info">全部分期</span>
              </div>
              <div class="payment-option" :class="{ 'selected': selectedPayment === 'friend' }" @click="selectPayment('friend')">
                <input type="radio" name="payment" :checked="selectedPayment === 'friend'" />
                <span class="payment-name">朋友代付</span>
              </div>
              <div class="payment-option" :class="{ 'selected': selectedPayment === 'insurance' }" @click="selectPayment('insurance')">
                <input type="radio" name="payment" :checked="selectedPayment === 'insurance'" />
                <span class="payment-name">号码保护</span>
              </div>
            </div> -->
          </div>
          
          <!-- 实付款 -->
          <div class="final-price">
            <div class="price-label">实付款</div>
            <div class="price-value">￥{{ finalPrice.toFixed(2) }}</div>
          </div>
          
          <!-- 提交订单按钮 -->
          <div class="submit-actions">
            <el-button 
              type="primary" 
              class="submit-btn"
              :loading="submitting"
              @click="submitOrder"
              :disabled="!selectedAddressId || submitting"
            >
              提交订单
            </el-button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 底部固定栏 -->
    <div class="bottom-bar">
      <div class="bottom-content">
        <div class="total-info">
          <span class="total-text">实付款：</span>
          <span class="total-price">￥{{ finalPrice.toFixed(2) }}</span>
        </div>
        <div class="back-button">
          <el-button @click="goBack">返回购物车</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getAddressListService } from '../../api/address'
import { addCartOrder } from '../../api/cart'
import router from '../../router'

// 地址数据类型
interface AddressItem {
  id: number
  name: string
  fullAddress: string
  phone: string
  isDefault: string
  province?: string
  city?: string
  district?: string
  detail?: string
}

// 商品数据类型
interface CartItem {
  id: string
  title: string
  image: string
  price: number
  num: number
  spec: string | Record<string, string>
  storeId?: string
  storeName?: string
}

// 按店铺分组的商品类型
interface StoreGroup {
  id: string
  name: string
  items: CartItem[]
}

// 地址列表
const addresses = ref<AddressItem[]>([])
// 选中的地址ID
const selectedAddressId = ref<number>(0)
// 订单备注
const orderRemark = ref<string>('')
// 选中的支付方式 - 暂时未使用，保留以备后续功能开发
// const selectedPayment = ref<string>('alipay')
// 提交订单加载状态
const submitting = ref<boolean>(false)
// 商品列表
const selectedItems = ref<CartItem[]>([])
// 运费
const shippingFee = ref<number>(0)
// 是否启用运费险
const enableInsurance = ref<boolean>(false)

// 从路由参数获取选中的商品
onMounted(async () => {
  // 从路由参数中获取选中的商品信息
  const routeItems = router.currentRoute.value.query.items
  if (routeItems) {
    try {
      // 解析从购物车传递过来的商品数据
      selectedItems.value = JSON.parse(decodeURIComponent(routeItems as string))
    } catch (error) {
      console.error('解析商品数据失败:', error)
      ElMessage.error('获取订单商品失败')
    }
  }
  
  // 获取地址列表
  await fetchAddressList()
})

// 获取地址列表
const fetchAddressList = async () => {
  try {
    const response = await getAddressListService()
    const addressData = response.data || []
    
    // 映射地址数据格式
    addresses.value = addressData.map((item: any) => ({
      id: item.id,
      name: item.contact,
      phone: item.mobile,
      isDefault: item.isDefault || '0',
      province: item.province,
      city: item.city,
      district: item.district,
      detail: item.detail,
      fullAddress: `${item.province}${item.city}${item.district}${item.detail}`
    }))
    
    // 默认选中默认地址或第一个地址
    if (addresses.value.length > 0) {
      const defaultAddress = addresses.value.find(item => item.isDefault === '1')
      selectedAddressId.value = defaultAddress ? defaultAddress.id : addresses.value[0].id
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
    ElMessage.error('获取地址列表失败')
  }
}

// 选择地址
const selectAddress = (addressId: number) => {
  selectedAddressId.value = addressId
}

// 打开新增地址页面（实际项目中应该跳转到地址管理页面）
const openAddAddress = () => {
  router.push('/account/address')
}

// 管理地址
const manageAddress = () => {
  router.push('/account/address')
}

// 返回购物车
const goBack = () => {
  router.push('/cart')
}

// 提交订单
const submitOrder = async () => {
  if (!selectedAddressId.value) {
    ElMessage.warning('请选择收货地址')
    return
  }
  
  try {
    submitting.value = true
    
    // 提取购物车ID集合
    const cartIds = selectedItems.value.map(item => Number(item.id))
    
    // 调用addCartOrder创建订单，传递购物车ID集合和地址ID
    const orderResponse: any = await addCartOrder(cartIds, selectedAddressId.value)
    
    // 检查响应是否成功
    if (orderResponse.code === 0 && orderResponse.data) {
      const orderData = orderResponse.data
      const orderId = orderData.orderId
      const amount = orderData.amount
      
      console.log('订单创建成功，订单ID:', orderId, '金额:', amount)
      ElMessage.success('订单创建成功！')
      
      // 跳转到支付页面
      router.push({
        path: '/payment',
        query: { 
          orderId: String(orderId),
          amount: String(amount)
        }
      })
    } else {
      ElMessage.error(orderResponse.message || '创建订单失败')
    }
  } catch (error: any) {
    console.error('提交订单失败:', error)
    ElMessage.error('提交订单失败: ' + (error.message || '网络错误'))
  } finally {
    submitting.value = false
  }
}

// 格式化规格信息
const formatSpec = (spec: string | Record<string, string>): string => {
  if (typeof spec === 'string') {
    return spec
  }
  return Object.entries(spec)
    .map(([key, value]) => `${key}: ${value}`)
    .join(' ')
}

// 手机号脱敏
const maskPhone = (phone: string): string => {
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// 计算商品总价
const totalPrice = computed(() => {
  return selectedItems.value.reduce((sum, item) => sum + (item.price * item.num), 0)
})

// 计算商品总数
const totalCount = computed(() => {
  return selectedItems.value.reduce((sum, item) => sum + item.num, 0)
})

// 按店铺分组的商品
const groupedItems = computed((): StoreGroup[] => {
  const groups: Record<string, StoreGroup> = {}
  
  selectedItems.value.forEach(item => {
    const storeId = item.storeId || 'default'
    const storeName = item.storeName || '宝可得店铺'
    
    if (!groups[storeId]) {
      groups[storeId] = {
        id: storeId,
        name: storeName,
        items: []
      }
    }
    
    groups[storeId].items.push(item)
  })
  
  return Object.values(groups)
})

// 计算最终价格（包含运费险）
const finalPrice = computed(() => {
  let price = totalPrice.value + shippingFee.value
  if (enableInsurance.value) {
    price += 4.53
  }
  return price
})
</script>

<style scoped lang="scss">
/* 重置和基础样式 */
* {
  box-sizing: border-box;
}

.order-confirm-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  overflow-x: hidden;
  padding-bottom: 60px; /* 为底部固定栏留出空间 */
}

.order-header {
  height: 50px;
  line-height: 50px;
  text-align: center;
  background-color: #fff;
  border-bottom: 1px solid #e8e8e8;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
}

.header-title {
  font-size: 16px;
  font-weight: 500;
}

.main-content {
  padding-top: 60px;
  display: flex;
  gap: 15px;
  max-width: 1200px;
  margin: 0 auto;
  padding-left: 15px;
  padding-right: 15px;
  box-sizing: border-box;
  min-height: calc(100vh - 60px);
}

/* 左侧内容区 */
.left-content {
  flex: 1;
  min-width: 0;
  width: calc(100% - 375px); /* 为右侧留出空间 */
}

/* 右侧内容区 */
.right-content {
  width: 360px;
  flex-shrink: 0;
  position: sticky;
  top: 70px;
  align-self: flex-start;
  height: calc(100vh - 140px);
  overflow-y: auto;
  padding-right: 5px;
}

/* 右侧滚动条样式 */
.right-content::-webkit-scrollbar {
  width: 4px;
}

.right-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2px;
}

.right-content::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 2px;
}

.right-content::-webkit-scrollbar-thumb:hover {
  background: #555;
}

.address-section,
.order-items-section,
.order-remark-section,
.delivery-section {
  background-color: #fff;
  margin-bottom: 10px;
  padding: 15px;
  border-radius: 4px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 15px;
  color: #333;
}

/* 地址选择区域样式 */
.address-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-bottom: 10px;
}

.address-cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
}

.address-card {
  border: 1px solid #e8e8e8;
  padding: 15px;
  border-radius: 4px;
  cursor: pointer;
  position: relative;
  background-color: #fff;
  transition: all 0.3s ease;
}

.address-card:hover {
  border-color: #ff6700;
  box-shadow: 0 2px 8px rgba(255, 103, 0, 0.1);
}

.address-card.selected {
  border-color: #ff6700;
  background-color: #fff5f0;
}

.address-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  flex-wrap: wrap;
}

.address-name {
  font-weight: 500;
  margin-right: 10px;
  color: #333;
}

.address-phone {
  color: #666;
  font-size: 14px;
}

.default-tag {
  font-size: 12px;
  color: #ff6700;
  border: 1px solid #ff6700;
  border-radius: 2px;
  padding: 2px 5px;
}

.address-detail {
  color: #666;
  line-height: 1.5;
  font-size: 14px;
  word-break: break-all;
}

.address-selected-marker {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 20px;
  height: 20px;
}

.check-icon {
  width: 20px;
  height: 20px;
  background-color: #ff6700;
  border-radius: 50%;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.check-icon::after {
  content: '';
  position: absolute;
  width: 5px;
  height: 10px;
  border-right: 2px solid #fff;
  border-bottom: 2px solid #fff;
  transform: rotate(45deg);
}

.no-address {
  text-align: center;
  padding: 30px 0;
  color: #999;
}

.no-address p {
  margin-bottom: 15px;
}

/* 订单商品信息 */
.no-items {
  text-align: center;
  padding: 30px 0;
  color: #999;
}

.store-group {
  margin-bottom: 15px;
}

.store-group:last-child {
  margin-bottom: 0;
}

.store-name {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 10px;
  color: #333;
}

.item {
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.item:last-child {
  border-bottom: none;
}

.item-info {
  display: flex;
}

.item-image {
  width: 80px;
  height: 80px;
  border: 1px solid #e8e8e8;
  margin-right: 15px;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.item-title {
  font-size: 14px;
  line-height: 1.4;
  color: #333;
  margin-bottom: 5px;
}

.item-spec {
  font-size: 12px;
  color: #999;
  margin-bottom: 5px;
}

.item-price-count {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-price {
  font-size: 14px;
  color: #ff6700;
  font-weight: 500;
}

.item-count {
  font-size: 12px;
  color: #999;
}

/* 商品汇总样式 */
.items-summary {
  margin-top: 15px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e9ecef;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.summary-row:last-child {
  margin-bottom: 0;
}

.summary-label {
  font-size: 14px;
  color: #666;
}

.summary-value {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.summary-value.price {
  color: #ff6700;
  font-size: 16px;
  font-weight: 600;
}

/* 订单备注 */
.remark-input {
  position: relative;
}

.remark-input textarea {
  width: 100%;
  height: 80px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  padding: 10px;
  resize: none;
  font-size: 14px;
}

.remark-count {
  position: absolute;
  bottom: 10px;
  right: 10px;
  font-size: 12px;
  color: #999;
}

/* 配送服务 */
.delivery-options {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.delivery-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0;
}

.option-name {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
  color: #333;
}

.option-desc {
  font-size: 12px;
  color: #999;
  margin-left: 25px;
}

.option-price {
  font-size: 14px;
  color: #666;
}

/* 右侧付款详情 */
.payment-details {
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
}

.price-items {
  margin-top: 10px;
}

.price-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.price-item:last-child {
  border-bottom: none;
}

.price-label {
  font-size: 14px;
  color: #666;
}

.price-value {
  font-size: 14px;
  color: #333;
}

.price-value.red {
  color: #ff6700;
}

/* 支付方式 */
.payment-methods {
  margin-top: 20px;
}

.payment-options {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.payment-option {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  padding: 5px 0;
}

.payment-option.selected {
  color: #ff6700;
}

.payment-name {
  font-size: 14px;
}

.installment-info {
  font-size: 12px;
  color: #999;
  margin-left: 5px;
}

/* 实付款 */
.final-price {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
}

.final-price .price-label {
  font-size: 16px;
  font-weight: 500;
}

.final-price .price-value {
  font-size: 18px;
  color: #ff6700;
  font-weight: 500;
}

/* 提交订单按钮 */
.submit-actions {
  margin-top: 20px;
}

.submit-btn {
  width: 100%;
  height: 44px;
  font-size: 16px;
  background-color: #ff6700;
  border-color: #ff6700;
}

.submit-btn:hover {
  background-color: #ff7a23;
  border-color: #ff7a23;
}

/* 底部固定栏 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 60px;
  background-color: #fff;
  border-top: 1px solid #e8e8e8;
  z-index: 99;
}

.bottom-content {
  max-width: 1200px;
  margin: 0 auto;
  height: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 15px;
}

.total-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.total-text {
  font-size: 14px;
  color: #666;
}

.total-price {
  font-size: 18px;
  color: #ff6700;
  font-weight: 500;
}

/* 响应式设计 - 确保大屏幕上显示左右分栏 */
@media (min-width: 1025px) {
  .main-content {
    flex-direction: row !important;
  }
  
  .left-content {
    width: calc(100% - 375px) !important;
  }
  
  .right-content {
    width: 360px !important;
    position: sticky !important;
    top: 70px !important;
    height: calc(100vh - 140px) !important;
  }
}

@media (max-width: 1200px) {
  .main-content {
    max-width: 100%;
  }
}

@media (max-width: 1024px) {
  .main-content {
    flex-direction: column;
  }
  
  .left-content {
    width: 100%;
  }
  
  .right-content {
    width: 100%;
    position: relative;
    top: 0;
    height: auto;
    overflow-y: visible;
    padding-right: 0;
  }
}

@media (max-width: 768px) {
  .address-cards {
    grid-template-columns: 1fr;
  }
  
  .main-content {
    padding-left: 10px;
    padding-right: 10px;
    gap: 10px;
  }
}
</style>